package structure.stack;

/**
 * @description: 单链表头插法实现栈结构
 * @author: wangjun
 * @create: 2022-04-22
 */
public class StackByLinkedList {

    private int maxSize = 3;
    private int initSize = 0;

    StackNode head = new StackNode(0);

    public StackByLinkedList(int maxSize) {
        this.maxSize = maxSize;
        this.initSize = 0;
    }

    public void push(StackNode node) {
        if (isNull()) {
            System.out.println("栈为空");
            return;
        }
        System.out.printf("入栈之前initSize:%d\n",initSize);
        if (initSize >= maxSize) {
            System.out.println("栈已满");
            System.out.printf("栈满之后initSize:%d",initSize);
            return;
        }
        if (head.next != null) {
            node.next = head.next;
        }
        head.next = node;
        initSize++;
        System.out.printf("入栈之后initSize:%d",initSize);
    }

    public void show() {
        if (isNull()) {
            System.out.println("栈为空");
            return;
        }
        StackNode temp = head;
        while (temp != null) {
            System.out.println(temp.next);
            temp = temp.next;
        }
    }

    public int pop() {
        if (isNull()) {
            return -1;
        }
        if (head.next == null) {
            return -1;
        }
        System.out.printf("出栈之前initSize:%d\n",initSize);
        if(initSize > 0){
            --initSize;
            System.out.printf("出栈之后initSize:%d\n",initSize);
        }
        int value = head.next.value;
        head.next = head.next.next;
        return value;
    }

    public boolean isNull() {
        return head == null;
    }
}